﻿package com.wmobile.ui;

import java.util.Date;

import com.wellsoft.mobileoa.R;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.MeasureSpec;
import android.view.View.OnClickListener;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;

public class RefreshListView extends ListView implements OnScrollListener {

	private static final String TAG = "listview";

	private final static int RELEASE_To_REFRESH = 0;
	private final static int PULL_To_REFRESH = 1;
	private final static int REFRESHING = 2;
	private final static int DONE = 3;
	private final static int LOADING = 4;

	// 各个控件之间的间隔为3
	private final static int RATIO = 3;

	private LayoutInflater inflater;

	private LinearLayout headView;

	private TextView tipsTextview;
	private TextView lastUpdatedTextView;
	private ImageView arrowImageView;
	private ProgressBar progressBar;

	private LinearLayout footView;

	private TextView footTipsTextview;
	private ProgressBar footProgressBar;

	private RotateAnimation animation;
	private RotateAnimation reverseAnimation;

	// 是否正在载入记录
	private boolean isRecorded;

	private int headContentWidth;
	private int headContentHeight;

	private int startY;

	// 当前显示的第一个项的索引值
	private int firstItemIndex;

	private int state;

	private int footstate;

	private boolean isBack;

	private OnRefreshListener refreshListener;

	private OnRefreshListener footRefreshListener;

	// 是否允许刷新
	private boolean isRefreshable;
	// 是否允许底部刷新
	private boolean isFootRefreshable;

	public RefreshListView(Context context) {
		super(context);
		init(context);
	}

	public RefreshListView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private void init(Context context) {
		inflater = LayoutInflater.from(context);

		headView = (LinearLayout) inflater.inflate(R.layout.refreshlisthead,
				null);

		arrowImageView = (ImageView) headView
				.findViewById(R.id.head_arrowImageView);
		arrowImageView.setMinimumWidth(70);
		arrowImageView.setMinimumHeight(50);
		progressBar = (ProgressBar) headView
				.findViewById(R.id.head_progressBar);
		tipsTextview = (TextView) headView.findViewById(R.id.head_tipsTextView);
		lastUpdatedTextView = (TextView) headView
				.findViewById(R.id.head_lastUpdatedTextView);

		measureView(headView);
		headContentHeight = headView.getMeasuredHeight();
		headContentWidth = headView.getMeasuredWidth();

		headView.setPadding(0, -1 * headContentHeight, 0, 0);
		headView.invalidate();

		Log.v("size", "width:" + headContentWidth + " height:"
				+ headContentHeight);

		addHeaderView(headView, null, false);

		footView = (LinearLayout) inflater.inflate(R.layout.refreshlistfoot,
				null);
		footTipsTextview = (TextView) footView.findViewById(R.id.footText_Tv);
		footProgressBar = (ProgressBar) footView.findViewById(R.id.footPgs_Pb);

		footView.setOnClickListener(footViewClickListener);
		addFooterView(footView);

		setOnScrollListener(this);

		animation = new RotateAnimation(0, -180,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		animation.setInterpolator(new LinearInterpolator());
		animation.setDuration(250);
		animation.setFillAfter(true);

		reverseAnimation = new RotateAnimation(-180, 0,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f,
				RotateAnimation.RELATIVE_TO_SELF, 0.5f);
		reverseAnimation.setInterpolator(new LinearInterpolator());
		reverseAnimation.setDuration(200);
		reverseAnimation.setFillAfter(true);

		state = DONE;
		footstate = DONE;
		isRefreshable = false;
		isFootRefreshable = false;
	}

	public void onScroll(AbsListView arg0, int firstVisiableItem, int arg2,
			int arg3) {
		firstItemIndex = firstVisiableItem;
	}

	public OnClickListener footViewClickListener = new OnClickListener() {

		public void onClick(View v) {
			if (isFootRefreshable) {
				switch (footstate) {
				case REFRESHING: {
					changeFooterViewByState();
					break;
				}
				case DONE: {
					footstate = REFRESHING;
					onFootRefresh();
					changeFooterViewByState();
					break;
				}
				default:
					break;
				}
			}
		}

	};

	public void onScrollStateChanged(AbsListView arg0, int arg1) {
	}

	public boolean onTouchEvent(MotionEvent event) {

		if (isRefreshable) {
			switch (event.getAction()) {
			case MotionEvent.ACTION_DOWN:
				if (firstItemIndex == 0 && !isRecorded) {
					isRecorded = true;
					startY = (int) event.getY();
					Log.v(TAG, "screen touched");
				}
				break;

			case MotionEvent.ACTION_UP:

				if (state != REFRESHING && state != LOADING) {
					if (state == DONE) {
						// finished
					}
					if (state == PULL_To_REFRESH) {
						state = DONE;
						changeHeaderViewByState();

						Log.v(TAG, "abandon refresh");
					}
					if (state == RELEASE_To_REFRESH) {
						state = REFRESHING;
						changeHeaderViewByState();
						onRefresh();

						Log.v(TAG, "begin refresh");
					}
				}

				isRecorded = false;
				isBack = false;

				break;

			case MotionEvent.ACTION_MOVE:
				// compare tempY with startY to judge the screen is moving up or
				// down
				int tempY = (int) event.getY();

				if (!isRecorded && firstItemIndex == 0) {
					Log.v(TAG, "move to first item");
					isRecorded = true;
					startY = tempY;
				}

				if (state != REFRESHING && isRecorded && state != LOADING) {

					// pulling

					// ready to refresh
					if (state == RELEASE_To_REFRESH) {

						setSelection(0);

						// check the distant between head and upboarder
						if (((tempY - startY) / RATIO < headContentHeight)
								&& (tempY - startY) > 0) {
							state = PULL_To_REFRESH;
							changeHeaderViewByState();

							Log.v(TAG, "pull down");
						}
						// refresh
						else if (tempY - startY <= 0) {
							state = DONE;
							changeHeaderViewByState();

							Log.v(TAG, "refresh done");
						}
						//
						else {
							//
						}
					}
					// check state change to release to refresh
					if (state == PULL_To_REFRESH) {

						setSelection(0);

						// release to refresh
						if ((tempY - startY) / RATIO >= headContentHeight) {
							state = RELEASE_To_REFRESH;
							isBack = true;
							changeHeaderViewByState();

							Log.v(TAG, "release to refresh");
						}
						// abandon refresh
						else if (tempY - startY <= 0) {
							state = DONE;
							changeHeaderViewByState();

							Log.v(TAG, "abandon refresh");
						}
					}

					// finished
					if (state == DONE) {
						if (tempY - startY > 0) {
							state = PULL_To_REFRESH;
							changeHeaderViewByState();
						}
					}

					//
					if (state == PULL_To_REFRESH) {
						headView.setPadding(0, -1 * headContentHeight
								+ (tempY - startY) / RATIO, 0, 0);

					}

					//
					if (state == RELEASE_To_REFRESH) {
						headView.setPadding(0, (tempY - startY) / RATIO
								- headContentHeight, 0, 0);
					}

				}

				break;
			}
		}

		return super.onTouchEvent(event);
	}

	//
	private void changeHeaderViewByState() {
		switch (state) {
		case RELEASE_To_REFRESH:
			arrowImageView.setVisibility(View.VISIBLE);
			progressBar.setVisibility(View.GONE);
			tipsTextview.setVisibility(View.VISIBLE);
			lastUpdatedTextView.setVisibility(View.VISIBLE);

			arrowImageView.clearAnimation();
			arrowImageView.startAnimation(animation);

			tipsTextview.setText("松开即更新");

			Log.v(TAG, "RELEASE_To_REFRESH");
			break;
		case PULL_To_REFRESH:
			progressBar.setVisibility(View.GONE);
			tipsTextview.setVisibility(View.VISIBLE);
			lastUpdatedTextView.setVisibility(View.VISIBLE);
			arrowImageView.clearAnimation();
			arrowImageView.setVisibility(View.VISIBLE);
			//
			if (isBack) {
				isBack = false;
				arrowImageView.clearAnimation();
				arrowImageView.startAnimation(reverseAnimation);

				tipsTextview.setText("下拉更新");
			} else {
				tipsTextview.setText("下拉更新");
			}
			Log.v(TAG, "PULL_To_REFRESH");
			break;

		case REFRESHING:

			headView.setPadding(0, 0, 0, 0);

			progressBar.setVisibility(View.VISIBLE);
			arrowImageView.clearAnimation();
			arrowImageView.setVisibility(View.GONE);
			tipsTextview.setText("更新中...");
			lastUpdatedTextView.setVisibility(View.VISIBLE);

			Log.v(TAG, "Loading...");
			break;
		case DONE:
			headView.setPadding(0, -1 * headContentHeight, 0, 0);

			progressBar.setVisibility(View.GONE);
			arrowImageView.clearAnimation();
			arrowImageView.setImageResource(R.drawable.arrow);
			tipsTextview.setText("更新完成");
			lastUpdatedTextView.setVisibility(View.VISIBLE);

			Log.v(TAG, "refresh done");
			break;
		}
	}

	//
	private void changeFooterViewByState() {
		switch (footstate) {
		case REFRESHING:

			footProgressBar.setVisibility(View.VISIBLE);
			footTipsTextview.setText("更新中...");

			Log.v(TAG, "Loading...");
			break;
		case DONE:

			footProgressBar.setVisibility(View.GONE);
			footTipsTextview.setText("点击查询更多");

			Log.v(TAG, "refresh done");
			break;
		}
	}

	public void setonRefreshListener(OnRefreshListener refreshListener) {
		this.refreshListener = refreshListener;
		isRefreshable = true;
	}

	public void setonFootRefreshListener(OnRefreshListener refreshListener) {
		this.footRefreshListener = refreshListener;
		isFootRefreshable = true;
	}

	public interface OnRefreshListener {
		public void onRefresh();
	}

	public void onRefreshComplete() {
		// 将底部的更新状态解开
		isFootRefreshable = true;
		state = DONE;
		lastUpdatedTextView.setText("最新更新时间:" + new Date().toLocaleString());
		changeHeaderViewByState();
	}

	private void onRefresh() {
		if (refreshListener != null) {
			// 将底部的更新状态锁定
			isFootRefreshable = false;
			refreshListener.onRefresh();
		}
	}

	public void onFootRefreshComplete() {
		// 将顶部的更新状态解开
		isRefreshable = true;
		footstate = DONE;
		changeFooterViewByState();
	}

	private void onFootRefresh() {
		if (footRefreshListener != null) {
			// 将顶部的更新状态锁定
			isRefreshable = false;
			footRefreshListener.onRefresh();
		}
	}

	// 获得头记录的长度与宽度
	private void measureView(View child) {
		ViewGroup.LayoutParams p = child.getLayoutParams();
		if (p == null) {
			p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
					ViewGroup.LayoutParams.WRAP_CONTENT);
		}
		int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
		int lpHeight = p.height;
		int childHeightSpec;
		if (lpHeight > 0) {
			childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
					MeasureSpec.EXACTLY);
		} else {
			childHeightSpec = MeasureSpec.makeMeasureSpec(0,
					MeasureSpec.UNSPECIFIED);
		}
		child.measure(childWidthSpec, childHeightSpec);
	}

	public void setAdapter(BaseAdapter adapter) {
		lastUpdatedTextView.setText("最新更新时间:" + new Date().toLocaleString());
		super.setAdapter(adapter);
	}
}